#include <pspkernel.h>
#include <pspdebug.h>
//#include <pspprof.h>
#include "config.h"
#include "rmff.h"
#include "rmff_queue.h"
#include "audio.h"
#include "video.h"
#include "shin_log.h"

PSP_MODULE_INFO("Shin", 0, 1, 1);
PSP_HEAP_SIZE_MAX();

rmff_file_t file;
rmff_stream_t *audiostream = 0, *videostream = 0;
SceUID main_tid = 0, audio_tid = 0, video_tid = 0;

int ExitThread(SceSize args, void *argp)
{
	if(audio_tid)sceKernelTerminateDeleteThread(audio_tid);
	if(video_tid)sceKernelTerminateDeleteThread(video_tid);
	if(main_tid)sceKernelTerminateDeleteThread(main_tid);
	rmff_close_file(&file);
//	gprof_cleanup();
	sceKernelExitGame();
	return 0;
}

void MyExit()
{
	SceUID tid;
	tid = sceKernelCreateThread("exit thread", ExitThread, 0x10, 0xFA0, 0, 0);
	sceKernelStartThread(tid, 0, 0);
	sceKernelSleepThread();
}

int ExitCallback(int arg1, int arg2, void *common)
{
	return ExitThread(0, 0);
}

int HomeThread(SceSize args, void *argp)
{
	int cbid = sceKernelCreateCallback("Exit Callback", (void*)ExitCallback, NULL);
	sceKernelRegisterExitCallback(cbid);
	sceKernelSleepThreadCB();
	return 0;
}

void SetupCallbacks(void)
{
	int tid = sceKernelCreateThread("home thread", HomeThread, 0x11, 0xFA0, 0, 0);
	if (tid >= 0)sceKernelStartThread(tid, 0, 0);
}

int main()
{
	rmff_packet_t *packet;
	rmff_stream_t *stream;
	char *filename;
	int i;

	main_tid = sceKernelGetThreadId();
	pspDebugScreenInit();
	SetupCallbacks();
	filename = "ms0:/test.rmvb";
	if(!rmff_open_file(filename, &file))fatal_log("Can't open specified file");
	if(rmff_read_headers(&file) < 0)fatal_log("Can't read headers");
	for(i = 0; i < file.num_streams && (!audiostream || !videostream); i++)
	{
		stream = &file.streams[i];
		if(!audiostream && stream->present && stream->type == STREAM_TYPE_AUDIO)audiostream = stream;
		if(!videostream && stream->present && stream->type == STREAM_TYPE_VIDEO)videostream = stream;
	}
	if(i == file.num_streams)
	{
		if(!audiostream)error_log("no audio stream found");
		if(!videostream)error_log("no video stream found");
	}
	if(audiostream)audio_tid = audio_init(audiostream);
	if(videostream)video_tid = video_init(videostream);
	while((packet = rmff_read_packet(&file)))
	{
		if(packet->stream->queue)
			rmff_queue_put_packet(packet->stream->queue, packet);
		else
			rmff_release_packet(packet);
	}
	debug_log("main over");
	MyExit();
	return 0;
}
